package com.xh.jf_blog.controller.admin;

import com.xh.jf_blog.bean.Userinfo;
import com.xh.jf_blog.common.form.LoginForm;
import com.xh.jf_blog.common.util.R;
import com.xh.jf_blog.service.UserinfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * @Author PangJunjie
 * @Date 2024/2/1/001
 */
@RequestMapping("/admin")
@Controller
public class AdminController {
    @Autowired
    private UserinfoService userinfoService;

    @GetMapping("/login")
    public String login() {
        return "admin/login";
    }

    /**
     * 系统后台登录
     *
     * @param loginForm
     * @param session
     * @return
     */
    @PostMapping("/login")
    @ResponseBody
    public R login(LoginForm loginForm, HttpSession session) {
        Userinfo userinfo = userinfoService.login(loginForm);
        if (userinfo != null) {
            if (userinfo.getRole() == 1 && userinfo.getStatus() == 1) {
                session.setAttribute("loginInfo", userinfo);
                return R.ok();
            } else {
                return R.error("账号异常！");
            }
        } else {
            return R.error("用户名或密码不正确！");
        }
    }

    @GetMapping("/home")
    public String home() {
        return "admin/home";
    }

    @GetMapping("/welcome")
    public String welcome() {
        return "admin/welcome";
    }

    @GetMapping("/nologin")
    public String noLogin() {
        return "admin/nologin";
    }

    @GetMapping("/logout")
    public String logout(HttpServletRequest request) {
        request.getSession().removeAttribute("loginInfo");
        return "redirect:/admin/login";
    }
}
